package com.unittec.zk.provider.exam.service;

import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.unittec.zk.provider.exam.utils.BeanMapper;
import com.unittec.zk.sdk.exam.domain.ExamRepoDTO;
import com.unittec.zk.sdk.root.internal.exception.BusinessException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unittec.zk.provider.exam.mapper.ElExamRepoMapper;
import com.unittec.zk.provider.exam.entity.ElExamRepo;
import org.springframework.util.CollectionUtils;

@Service
public class ElExamRepoService extends ServiceImpl<ElExamRepoMapper, ElExamRepo> {

    public void saveAll(String examId, List<ExamRepoDTO> list) {
        // 先删除
        QueryWrapper<ElExamRepo> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ElExamRepo::getExamId, examId);
        this.remove(wrapper);

        // 再增加
        if(CollectionUtils.isEmpty(list)){
            throw new BusinessException("必须选择题库！");
        }
        List<ElExamRepo> repos = BeanMapper.mapList(list, ElExamRepo.class);
        for(ElExamRepo item: repos){
            item.setExamId(examId);
            item.setId(IdWorker.getIdStr());
        }

        this.saveBatch(repos);
    }

    public List<ExamRepoDTO> listByExam(String examId) {
        QueryWrapper<ElExamRepo> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ElExamRepo::getExamId, examId);
        List<ElExamRepo> list = this.list(wrapper);
        List<ExamRepoDTO> dtoList = new ArrayList<>();

        if(!CollectionUtils.isEmpty(list)){
            dtoList = BeanMapper.mapList(list, ExamRepoDTO.class);
        }
        return dtoList;
    }
}
